/**     
* @Title: CrawlManager.java   
* @Package me.crawler.entry
* @Description: TODO   
* @author xaoyaoyao
* @date 2019年1月13日 下午3:30:27
*/
package me.crawler.entry;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import me.crawler.dto.PoetryDtos;
import me.crawler.processor.AbstractProcessor;
import me.crawler.processor.impl.PoetryProcessor;
import me.crawler.util.StopSignalReceiver;

/**
 * @ClassName: CrawlManager
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2019年1月13日 下午3:30:27
 * 
 */
@Slf4j
@Service
public class CrawlManager {

	private int poolSize = 2;

	@Autowired
	private PoetryProcessor poetryProcessor;

	public CrawlManager() {
	}

	public ThreadPoolExecutor execute() {
		log.error(">>>>>>>> 程序进入执行任务状态！");
		// 配置线程池
		ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(poolSize + 1, poolSize + 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(poolSize + 1),
				new ThreadPoolExecutor.CallerRunsPolicy());
		// 添加任务到线程池
		for (int i = 0; i < poolSize; i++) {
			poolExecutor.execute(new PoetryThread(poetryProcessor, false));
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
		}
		// 进入任务管理状态
		while (!isExit() || poolExecutor.getCompletedTaskCount() != poolSize) {
			try {
				Thread.sleep(15000);
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
		}
		return poolExecutor;
	}

	private boolean isExit() {
		return StopSignalReceiver.isReceived();
	}
}
